import math
import time
import os
import sys

# 将工程目录加入包扫描
currPath = os.path.abspath(os.path.dirname(__file__))
srcPath = os.path.split(currPath)[0]
rootPath = os.path.split(srcPath)[0]
projectPath = os.path.split(rootPath)[0]
sys.path.append(projectPath)

from src.db.CcxDataCenterDb import CcxDataCenter
from src.db.ProdDb import ProdDb
from src.utils.LogUtils import Logger

logger = Logger()


class syncQeIndex:
    def __init__(self, logger, localDb, dataCenterDb):
        self.logger = logger
        self.localDb = localDb
        self.dataCenterDb = dataCenterDb

    def __queryQeIndex__(self):
        sql = """
        SELECT * FROM qe_index 
        """
        return self.dataCenterDb.Query(sql)

    def __deleteQeIndex__(self):
        sql = """
        DELETE from qe_index 
        """
        return self.localDb.Query(sql, None)

    def __save_db__(self, data):
        regionSql = """
        REPLACE INTO qe_index
            (parent,code,name)
            VALUES
            (%(parent)s,%(code)s,%(name)s);
        """

        temp = []
        for i in data:
            data = {
                "parent": i["parent"],
                "code": i["code"],
                "name": i["name"],
            }
            temp.append(data)
        logger.info("数据一共%s条" % len(temp))
        self.localDb.ExecMany(regionSql, temp, 1000)


if __name__ == "__main__":
    logger = Logger()
    localDb = ProdDb(logSql=False, autocommit=True)
    dataCenterDb = CcxDataCenter(logSql=False, autocommit=True)
    t = time.perf_counter()
    logger.info("========同步qe数据 开始 ========")
    syncData = syncQeIndex(logger=logger, localDb=localDb, dataCenterDb=dataCenterDb)
    # 删除数据
    syncData.__deleteQeIndex__()
    data = syncData.__queryQeIndex__()
    syncData.__save_db__(data)
    cast = (time.perf_counter() - t)
    m = math.floor(cast / 60)
    s = cast - m * 60
    logger.info('总耗时: %d分%.3f秒' % (m, s))
    logger.info("========同步qe数据 结束 ========")
